package com.catemanagement.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.xml.sax.SAXException;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.util.Log;

/**
 * 
 * 实现软件更新的管理类
 */
public class UpdateManager {

    // 保存解析的XML信息
    HashMap<String, String> mHashMap;

    private String tag = "UpdateManager";

    private Context mContext;

    public UpdateManager(Context context) {
        super();
        mContext = context;
    }

    /**
     * 检查软件是否有更新版本
     * 
     * @return
     * @throws URISyntaxException
     * @throws IOException
     * @throws ClientProtocolException
     * @throws SAXException
     * @throws ParserConfigurationException
     */
    public boolean isUpdate() throws URISyntaxException, ClientProtocolException, IOException,
            ParserConfigurationException, SAXException {

        // 获取当前软件版本
        int versionCode = getVersionCode(mContext);
        // 把version.xml放到网络上，然后获取文件信息

        URL url = new URL(Constants.UPDATE_URL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        // 创建输入流
        InputStream inStream = conn.getInputStream();

        // 解析XML文件。 由于XML文件比较小，因此使用DOM方式进行解析
        ParseXmlUtil service = new ParseXmlUtil();

        mHashMap = service.parseXml(inStream);

        if (null != mHashMap) {
            int serviceCode = Integer.valueOf(mHashMap.get("version"));
            // 版本判断
            if (serviceCode > versionCode) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取软件版本号
     * 
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        // TODO Auto-generated method stub
        int versionCode = 0;

        // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
        try {
            versionCode = context.getPackageManager().getPackageInfo("com.catemanagement", 0).versionCode;
        } catch (NameNotFoundException e) {
            Log.e(tag, e.getMessage(), e);
        }
        return versionCode;
    }

    public void update() {
        try {
            String url = mHashMap.get("url");
            Uri uri = Uri.parse(url);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(it);
        } catch (Exception e) {
            Log.e(tag, e.getMessage(), e);
        }
    }

}
